<?php

namespace app\command\controller;

use app\common\model\BalanceTotal;
use app\common\model\WithdrawalOrder;
use think\Controller;
use think\Db;

class Balance extends Controller
{
    public function countBalance(){
        $date = date("Y-m-d", strtotime("-1 day"));
        $moneyIds = Db::name("money_log")->where('from_unixtime(trading_time,"%Y-%m-%d") = "'.$date.'"')->group("main_id")->column("main_id");
        $withdrawalIds = Db::name("withdrawal_order")->where(["payment_status" => 2,"status" => 1,"audit_status" => 2])
            ->where('from_unixtime(payment_time,"%Y-%m-%d") = "'.$date.'"')->group("sale_id")->column("sale_id");
        $orderIds = Db::name("order")->where(['pay_type' => 1,"pay_state" => 1])->where('from_unixtime(pay_time,"%Y-%m-%d") = "'.$date.'"')->group("user_id")->column("user_id");

        $userIds = array_unique(array_merge($moneyIds,$withdrawalIds,$orderIds));

        if (count($userIds) > 0){
            foreach ($userIds as $key => $val){
                $income = Db::name("money_log")->where(['main_type' => 2,'main_id' => $val])
                    ->where('from_unixtime(trading_time,"%Y-%m-%d") = "'.$date.'"')
                    ->field("IFNULL(Sum(changes),0) as all_money,count(id) as total")
                    ->find();
                $withdrawal = Db::name("withdrawal_order")->where(["main_type" => 2,"sale_id" => $val,"payment_status" => 2,"status" => 1,"audit_status" => 2])
                    ->where('from_unixtime(payment_time,"%Y-%m-%d") = "'.$date.'"')
                    ->field("IFNULL(SUM(withdrawal_money), 0) as all_money,COUNT(id) as total")
                    ->find();
                $order = Db::name("order")->where(['pay_type' => 1,"pay_state" => ["in",[1,2]],"user_id" => $val])
                    ->where('from_unixtime(pay_time,"%Y-%m-%d") = "'.$date.'"')
                    ->field("IFNULL(SUM(pay_price), 0) as all_money,COUNT(id) as total")
                    ->find();

                $expend = $withdrawal['all_money'] + $order['all_money'];
                $expendBit = $withdrawal['total'] + $order['total'];

                Db::startTrans();
                try {
                    $balance = \app\common\model\Balance::where(["main_type" => 2, "main_id" => $val])->find();
                    if ($balance) {
                        $before = $balance->money;
                    } else {
                        $balance = new \app\common\model\Balance();
                        $balance->main_type = 2;
                        $balance->main_id = $val;
                        $balance->total = 0;
                        $before = 0;
                    }

                    $after = $before + $income['all_money'];

                    $balance->money = $after;
                    $balance->total += $income['all_money'];
                    $balance->save();

                    $balanceTotal = new BalanceTotal();
                    $balanceTotal->main_type = 2;
                    $balanceTotal->main_id = $val;
                    $balanceTotal->date = $date;
                    $balanceTotal->income = $income['all_money'];
                    $balanceTotal->income_bit = $income['total'];
                    $balanceTotal->expend = $expend;
                    $balanceTotal->expend_bit = $expendBit;
                    $balanceTotal->before = $before;
                    $balanceTotal->after = $after;
                    $balanceTotal->save();
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    echo $e->getMessage();
                }
            }
        }
    }

    public function setBalance()
    {
        $date = date("Y-m-d", strtotime("-1 day"));
//        $sql = 'SELECT main_type,main_id,Sum(changes) as all_money,count(id) as total,from_unixtime(trading_time,"%Y-%m-%d") as date FROM fd_money_log where trading_time < 1684252800 GROUP BY main_type,main_id,date ORDER BY date asc';
        $sql = 'SELECT main_type,main_id,Sum(changes) as all_money,count(id) as total,from_unixtime(trading_time,"%Y-%m-%d") as date FROM fd_money_log where from_unixtime(trading_time,"%Y-%m-%d") = "'.$date.'" GROUP BY main_type,main_id,date ORDER BY date asc';
        $list = Db::query($sql);

        $arr = [];//已计算提现的ID
        foreach ($list as $key => $val) {
            Db::startTrans();
            try {
                $withdrawal = WithdrawalOrder::where(["main_type" => $val['main_type'],"sale_id" => $val['main_id'],"payment_status" => 2,"status" => 1,"audit_status" => 2])
                    ->where('from_unixtime(payment_time,"%Y-%m-%d") = "'.$val['date'].'"')
                    ->group("sale_id")
                    ->field("IFNULL(SUM(withdrawal_money), 0) as all_money,COUNT(id) as total")
                    ->find();

                if($withdrawal->all_money > 0){
                    $arr[] = $val['main_id'];
                }

                $balance = \app\common\model\Balance::where(["main_type" => $val['main_type'], "main_id" => $val['main_id']])->find();
                if ($balance) {
                    $before = $balance->money;
                } else {
                    $balance = new \app\common\model\Balance();
                    $balance->main_type = $val['main_type'];
                    $balance->main_id = $val['main_id'];
                    $balance->total = 0;
                    $before = 0;
                }

                $after = $before + $val['all_money'];

                $balance->money = $after;
                $balance->total += $val['all_money'];
                $balance->save();

                $balanceTotal = new BalanceTotal();
                $balanceTotal->main_type = $val['main_type'];
                $balanceTotal->main_id = $val['main_id'];
                $balanceTotal->date = $val['date'];
                $balanceTotal->income = $val['all_money'];
                $balanceTotal->income_bit = $val['total'];
                $balanceTotal->expend = $withdrawal->all_money;
                $balanceTotal->expend_bit = $withdrawal->total;
                $balanceTotal->before = $before;
                $balanceTotal->after = $after;
                $balanceTotal->save();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                var_dump($e->getMessage());
            }
        }

        $withdrawalList = WithdrawalOrder::where(["payment_status" => 2,"status" => 1,"audit_status" => 2])
            ->where('from_unixtime(payment_time,"%Y-%m-%d") = "'.$date.'"')
            ->where("sale_id","not in",$arr)
            ->group("main_type,sale_id")
            ->field("main_type,sale_id,IFNULL(SUM(withdrawal_money), 0) as all_money,COUNT(id) as total")
            ->select();
        if(count($withdrawalList) > 0){
            foreach ($withdrawalList as $key => $val){
                $total = BalanceTotal::where(["main_type" => $val->main_type,"main_id" => $val->sale_id,"date" => $date])->find();
                if(!$total){
                    $last = BalanceTotal::where(["main_type" => $val->main_type,"main_id" => $val->sale_id])->order("date desc")->find();
                    $before = $last->after;
                    $balanceTotal = new BalanceTotal();
                    $balanceTotal->main_type = $val->main_type;
                    $balanceTotal->main_id = $val->sale_id;
                    $balanceTotal->date = $date;
                    $balanceTotal->expend = $val->all_money;
                    $balanceTotal->expend_bit = $val->total;
                    $balanceTotal->before = $before;
                    $balanceTotal->after = $before - $val->all_money;
                    $balanceTotal->save();
                }
            }
        }
    }
}
